#include "player.h"
#include <QPixmap>
#include "GameSetting.h"
#include <QKeyEvent>
#include <QGraphicsScene>
#include <enemy.h>
#include <bullet.h>
#include "health.h"
#include <QGraphicsTextItem>
#include <QFontMetrics>
#include "score.h"
using namespace GameSetting;
Player::Player(QGraphicsItem *parent):QGraphicsPixmapItem(parent)
{
    bulletSound.setSource(QUrl("qrc:/images/Sprites/sounds/BulletWav.wav"));
    setPixmap(QPixmap(":/images/Sprites/hero/fly/hero1.png"));
    setScale(PlayerScale);
    setPos(SceneWidth/2-boundingRect().width()*PlayerScale/2,
           SceneHeight-boundingRect().height()*PlayerScale); //设置飞机初始位置
    setFlag(QGraphicsItem::ItemIsFocusable); //聚焦
    setFocus();
    startTimer(PlayerTimer);//间期半秒钟


}


void Player::keyPressEvent(QKeyEvent *event)
{
    switch(event->key()){
    case Qt::Key_Left: //左移
        if(pos().x()>0)
            setPos(x()-PlayerMoveSpeed,y());
        break;
    case Qt::Key_Right: //右移
        if(pos().x()<SceneWidth-boundingRect().width()*PlayerScale)
            setPos(x()+PlayerMoveSpeed,y());
        break;
    case Qt::Key_S: //按s键重新开始游戏
        if(playing) return;
        playing =true;
        Health::getInstance().reset();
        Score::getInstance().reset();
        messageItem->hide();
        break;
    case Qt::Key_Space: //空格发射子弹
        bulletSound.play();
        Bullet *bullet=new Bullet;
        int temp=x()+boundingRect().width()*PlayerScale/2; //子弹位移到飞机中间偏右
        temp-=bullet->boundingRect().width()*BulltScale/2; //子弹位移到飞机正中间
        bullet->setPos(temp,y());
        scene()->addItem(bullet);
        //播放音效
        break;
    }    
}

void Player::enemySpawn()
{
    Enemy *enemy=new Enemy;
    scene()->addItem(enemy);
}

void Player::gameOver()
{
    playing=false;
    for(auto item:scene()->items()){
        if(typeid(*item)==typeid(Enemy)){
            scene()->removeItem(item);
            delete item;
        }
    }
    if(!messageItem){
        messageItem=new QGraphicsTextItem;
        scene()->addItem(messageItem);
        QString message("Game Over!按S键重新开始!");
        messageItem->setPlainText(message);
        messageItem->setDefaultTextColor(Qt::black);
        QFont font("Courier New",GameSetting::FontSize,QFont::Bold);
        messageItem->setFont(font);
        QFontMetrics fm(font);
        int msgWidth=fm.horizontalAdvance(message);
        messageItem->setPos(GameSetting::SceneWidth/2-msgWidth/2,
                            GameSetting::SceneHeight/2);
    }else{
        messageItem->show();
    }

}



void Player::timerEvent(QTimerEvent *event)
{
    Q_UNUSED(event);
    if(playing) enemySpawn();
    if(Health::getInstance().getHealth()<=0) gameOver(); //血量归零,游戏结束
}
